package beans;
import toolbox.DBconne;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.*;
import java.util.*;
import java.text.*;

public class UserBean implements Serializable{
	private static final long serialVersionUID = 1L;
	String username;
	String password;
	
	public UserBean() {
		super();
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public boolean isUnique()
	{
		Connection con = DBconne.getConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "select * from User where user=?";
		boolean ret = false; 
		try{
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, this.username);
			rs = pstmt.executeQuery();	
			
			if(rs==null){
				System.out.println("Wrong here!");
				return ret;
			}
			if(!rs.next()) ret = true;
			
			pstmt.close();
			DBconne.closeConnection();
			
		} catch (SQLException e){
			System.out.println("SQLException in UserBean  line 49!");
		}
		return ret;
	}
	public boolean addUser()
	{
		Connection con = DBconne.getConnection();
		PreparedStatement pstmt = null;
		String sql = "insert into User(user,passwd,type,createtime) values(?,?,?,?)";
		int value = 0;
		Date now = new Date();
		DateFormat df = DateFormat.getDateTimeInstance();
		String createtime = df.format(now);
		System.out.println("User are created at "+createtime);
		try{
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, this.username);
			pstmt.setString(2,this.password);
			pstmt.setInt(3, 0);
			pstmt.setString(4, createtime);
			value=pstmt.executeUpdate();
		} catch (SQLException e){
			e.printStackTrace();
		} finally {
			try
			{
				if(pstmt!=null){
					pstmt.close();
				}
				DBconne.closeConnection();
			}
			catch (SQLException ee)	{}
		}
		if(value==1) return true;
		else return false;
	}
}
